<?php
class FbAudienceController extends BaseController {
	public static $_TOTAL_REQ_FEED = 100;
	public static $_LIMIT_REQ = 50;
	const verifyToken = 'THAODX';
	const _LIMIT = 25;
	function getPost() {
		$feeds = [];
		$pattern = '/(((https?:\/\/)?(www\.)?facebook\.com\/))?(.*\/)?([a-zA-Z0-9.]*)($|\?.*)/';
		if( Input::has('pageurl') && preg_match($pattern, Input::get('pageurl'), $match)) {
			#$fbPage = Input::get('pageurl');
			$fbPage = $match[6];
			$feeds = self::_getPagePost($fbPage);
		}
		return View::make('fbaudience.get-post')
				->with('feeds', $feeds);
	}
	public static function getIdsByPosts() {
		dd($_GET);
	}
	public static function fbRealTimeSub() {
		$apiUrl = Config::get('app.fbapi') . Config::get('facebook.appId') . '/subscriptions?access_token=' . self::getFbAppToken();
		$params = array(
			'object' => 'page'
			, 'callback_url' => URL::to('/fbcallback')
			, 'fields' => 'category,company_overview,description,feed,founded,general_info,general_manager,location,members,mission,name,picture,productlists'
			, 'verify_token' => self::verifyToken
		);

		return HomeController::curl($apiUrl, $params);
	}
	public static function getFbAppToken() {
		$apiUrl = 'https://graph.facebook.com/oauth/access_token?client_id='.Config::get('facebook.appId').'&client_secret='.Config::get('facebook.secret').'&grant_type=client_credentials';
		$response = HomeController::curl($apiUrl);
		return str_replace('access_token=', '', $response);
	}
	function _getPagePost( $fbPage, $total = null) {
		$arrFeed = array();
		if( $total === null) $total = self::$_TOTAL_REQ_FEED;
		$edge = null;
		if( $total > self::$_LIMIT_REQ) {
			$page = ceil( $total / self::$_LIMIT_REQ);
			$offset = 0;
			$arrBatch = [];
			$edge = '';

			for( $i = 1; $i <= $page; $i++) {
				$edge = Config::get('app.apiversion') . $fbPage . 
						'/posts?fields=id,message,link,object_id,picture,shares,type,likes.summary(true),comments.summary(true),created_time&limit=' . self::$_LIMIT_REQ . 
						'&offset=' . $offset;

				$offset = $i * self::$_LIMIT_REQ;
				array_push($arrBatch, array(
					'relative_url' => $edge,
					'include_headers' => false
				));
			}
			$batchParams = json_encode($arrBatch);
			if(!empty($batchParams)){
				$apiUrl = Config::get('app.fbapi') . '?access_token=' . Auth::user()->access_token;

				$apiResponse = HomeController::curl($apiUrl, array('batch' => $batchParams, 'include_headers' => false));
				try{
					$objFeed = json_decode($apiResponse, true);
					if( isset($objFeed['error'])) {
						return $objFeed['error']['message'];
					}
					foreach ($objFeed as $key => $feeds) {
						$pageFeed = json_decode($feeds['body'],true);
						if(empty($pageFeed['data'])) continue;
						foreach($pageFeed['data'] as $v => $feeds){
							array_push($arrFeed, $feeds);
						}
					}
				}
				catch(Exception $e){
					echo $e->getMessage();
				}
			}
		}
		return $arrFeed;
	}
	function callback() {
		/*file_put_contents(base_path() . '/logs.txt', date('d/m/Y H:i:s' . "\n"), FILE_APPEND);
		file_put_contents(base_path() . '/logs.txt', "POST: " . print_r($_POST, true), FILE_APPEND);
		file_put_contents(base_path() . '/logs.txt', "GET: ". print_r($_GET, true) . "\n", FILE_APPEND);*/
		$verify_token = self::verifyToken;

		if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['hub_mode'])
		&& $_GET['hub_mode'] == 'subscribe' && isset($_GET['hub_verify_token'])
		&& $_GET['hub_verify_token'] == $verify_token) {
		  echo $_GET['hub_challenge'];
		} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$post_body = file_get_contents('php://input');
			$obj = json_decode($post_body, true);
			// $obj will contain the list of fields that have changed
			$nodeServer = 'http://127.0.0.1:81';
			$token = 'DKMCLGT';
			$uid = null;

			if (!empty($obj['entry'])) {
				foreach ($obj['entry'] as $item) {
					// get user id by facebook page id
					$userInfo = Fbpage::select('user_id')->where('fb_page_id', $item['id'])->get();
					foreach($userInfo as $user) {
						HomeController::curl($nodeServer, array(
							"channel" => Fbpage::generateUserChannel($user->user_id),
							"key" => $token,
							"data" => json_encode($item)
						));
					}
				}
			}
			/*
			file_put_contents(base_path() . '/logs.txt', "OBJ: ". print_r($obj, true) . "\n", FILE_APPEND);
			*/
		}
	}

	function checknode() {
		$nodeServer = 'http://127.0.0.1:81';
		$token = 'DKMCLGT';
		$uid = 3;
		echo HomeController::curl($nodeServer, array(
			"channel" => Fbpage::generateUserChannel($uid),
			"key" => $token,
			"data" => json_encode(array('name' => 'thaodx'))
		));
		exit(0);
	}

	function pagePost() {
		/*$objPHPExcel = PHPExcel_IOFactory::load(public_path() . '/fbtarget.xlsx');
	    $objWorksheet = $objPHPExcel->getSheetByName('Sheet1');
		var_dump($objWorksheet->getHeaderFooter()->getImages());die;
	    foreach ($objWorksheet->getDrawingCollection() as $drawing) {
	    	$string = $drawing->getCoordinates();
	    	$coordinate = PHPExcel_Cell::coordinateFromString($string);
	    	if ($drawing instanceof PHPExcel_Worksheet_Drawing){
				$filename = $drawing->getPath();
				$drawing->getDescription();
				echo $drawing->getDescription();
				copy($filename, public_path() . '/' . $drawing->getDescription());
			}
	    }*/
		return View::make('page-post')
		->with('pages', Fbpage::where('user_id', Auth::user()->id)->get())
		->with('pageposts', Pagepost::join('fbpages', 'pageposts.page_id', '=', 'fbpages.id')->where('pageposts.user_id', Auth::user()->id)->orderBy('pageposts.id', 'desc')->paginate(self::_LIMIT))
		->with('tab', Input::get('tab'))
		->with('input', Input::old());
	}
	function createPagePost() {
		$params = array(
			'pages' 	=> Input::get('fbpage'),
			'message' 	=> Input::get('message'),
			'picture' 	=> Input::get('picture'),
			'link' 		=> Input::get('link'),
			'name' 		=> Input::get('name'),
			'caption' 	=> Input::get('caption'),
			'desc' 		=> Input::get('desc'),
			'pdate' 	=> Input::get('pdate'),
			'ptime' 	=> Input::get('ptime'),
			'photo' 	=> null,
		);
		$tab = 'pp';
		if(!empty($_FILES['photo']['name'])) {
			$photo = Input::file('photo');
			$filename = $photo->getClientOriginalName();
			$filename = pathinfo($filename, PATHINFO_FILENAME);
			$extension = strtolower($photo->getClientOriginalExtension());
			// We should salt and make an url-friendly version of the file
	        $fullname = Str::slug(Str::random(8) . $filename) . '.' .
	            $extension;
	        $todayFolder = date('Ymd');
			$uploadFolder = public_path() . '/uploads/' . $todayFolder . '/';
			$arrExt = Config::get('app.allowedExt');

			if (!in_array($extension, $arrExt)) {
				return Redirect::back()->withInput()->with('result', array(array('error' => array('message' => 'File type does not match. Only <strong>' . implode(',', $arrExt) . '</strong> are allowed.'))));
			}
			$photo->move($uploadFolder, $fullname);
			$imgPath = '/uploads/' . $todayFolder . '/' . $fullname;

			$params['photo'] = $imgPath;
			$params['message'] = Input::get('status');
			$tab = 'pf';
		}
		$result = Fbpage::createPagePost($params);
		return Redirect::to('/page-post?tab=' . $tab)->withInput()->with('result', $result);
	}

	function pageTab() {
		// add tab
		// http://facebook.com/add.php?api_key=1473724626177261&pages=1&page=250726868433104
		if( Input::exists('signed_request')) {
			$signed_request = $_REQUEST['signed_request'];
			$data = Fbpage::getSingnedRequest($signed_request);
			echo '<!--';
			print_r($data);
			echo '-->';
		}
		return View::make('page-tab');
	}
	function csvMassImport() {
		if(Input::has('message')) {
			$messages = explode('--BREAK--', Input::get('message'));
			$pictures = explode('--BREAK--', Input::get('picture'));
			$links = explode('--BREAK--', Input::get('link'));
			$names = explode('--BREAK--', Input::get('name'));
			$captions = explode('--BREAK--', Input::get('caption'));
			$descs = explode('--BREAK--', Input::get('desc'));
			$params = array(
				'page_id' 	=> Input::get('fbpage'),
				'messages' 	=> $messages,
				'pictures' 	=> $pictures,
				'links' 	=> $links,
				'names' 	=> $names,
				'captions' 	=> $captions,
				'descs' 	=> $descs,
				'pdate' 	=> Input::get('pdate'),
				'ptime' 	=> Input::get('ptime'),
				'photo' 	=> null,
			);
			$result = Fbpage::createMassPagePost($params);
			return Redirect::to('/fb-audience/mass-importer')->withInput()->with('result', $result);
		}
		/*$csvFile = 'E:/projects/target/mass-post-template.csv';

		$csv = CsvReader::get($csvFile); 
		$data = $csv->toArray();
		unset($csv[0]);
		foreach($csv as $item)
		{
		    var_dump($item);
		}
		die;*/
		return View::make('fbaudience.mass-importer')
			->with('pages', Fbpage::where('user_id', Auth::user()->id)->get())
			->with('input', Input::old());
	}
}